package com.java80.littlegame.service.gateway.websocket;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hazelcast.config.Config;
import com.java80.littlegame.common.base.BaseHandler;
import com.java80.littlegame.common.base.BaseVerticle;
import com.java80.littlegame.common.base.Runner;
import com.java80.littlegame.common.base.ServiceStatus;
import com.java80.littlegame.common.base.SystemConsts;
import com.java80.littlegame.common.base.SystemDataMgr;
import com.java80.littlegame.common.base.VertxMessageHelper;
import com.java80.littlegame.service.gateway.websocket.net.WebSocketServer;

import io.vertx.core.DeploymentOptions;
import io.vertx.core.VertxOptions;
import io.vertx.core.eventbus.EventBus;
import io.vertx.spi.cluster.hazelcast.HazelcastClusterManager;

public class GatewayVerticle extends BaseVerticle {
	final transient static Logger log = LoggerFactory.getLogger(GatewayVerticle.class);

	public static void main(String[] args) {
		Thread t = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				WebSocketServer server = new WebSocketServer();
				try {
					server.start();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});
		t.start();
		Runner.run(GatewayVerticle.class,
				new VertxOptions()
						.setClusterManager(new HazelcastClusterManager(new Config(GatewayConfig.getInstanceName())))
						.setClustered(true));

	}

	@Override
	public String queueName() {
		return GatewayConfig.getQueueName();
	}

	@Override
	public BaseHandler getHandler() {
		return new GatewayHandler();
	}

	@Override
	public ServiceStatus getServiceStatus() {
		ServiceStatus ss = new ServiceStatus();
		ss.setInstanceName(GatewayConfig.getInstanceName());
		ss.setServiceId(GatewayConfig.getServiceId());
		ss.setServiceQueueName(GatewayConfig.getQueueName());
		ss.setServiceType(SystemConsts.SERVICE_TYPE_GATEWAY);
		return ss;
	}

	@Override
	public void start() throws Exception {

		// super.start();
		SystemDataMgr.loadSystemData();
		EventBus eventBus = vertx.eventBus();
		vertx.deployVerticle(VertxMessageHelper.class, new DeploymentOptions().setWorker(true).setInstances(3));
		// eventBus.registerDefaultCodec(BaseMsg.class, new VertxMsgCodec());
		String queueName = queueName();
		if (StringUtils.isNotBlank(queueName)) {
			eventBus.consumer(queueName(), msg -> {
				String json = msg.body().toString();
				log.info("收到来自集群的消息：->{}", json);
				getHandler().onReceive(json);
			});
		}

		if (needPublishServiceStatus()) {
			publishService();
		}
		log.info("service start success! {}", GatewayConfig.getServiceId());
	}

	@Override
	public boolean needPublishServiceStatus() {
		return true;
	}

}
